import { ref, reactive } from 'vue'
import { useMessage } from 'naive-ui'

export function useTopologyEditor() {
  const message = useMessage()
  
  // 节点数据 - 清空初始节点
  const nodes = ref([])
  
  // 边数据
  const edges = ref([])
  
  // 选中的节点类型
  const selectedNodeType = ref(null)

  // 当前选中的边
  const selectedEdge = ref(null)
  
  // 节点变化处理
const handleNodesChange = (changes) => {
  // 仅应用 VueFlow 的增量更新
  changes.forEach(change => {
    if (change.type === 'add') {
      nodes.value = [...nodes.value, change.item]
    } else if (change.type === 'remove') {
      nodes.value = nodes.value.filter(node => node.id !== change.id)
    } else if (change.type === 'update') {
      nodes.value = nodes.value.map(node =>
        node.id === change.id ? { ...node, ...change.item } : node
      )
    }
  })
}
  
  // 边变化处理
  const handleEdgesChange = (changes) => {
    changes.forEach(change => {
      if (change.type === 'add') {
        edges.value = [...edges.value, change.item]
      } else if (change.type === 'remove') {
        edges.value = edges.value.filter(edge => edge.id !== change.id)
        // 如果删除的是选中的边，清空选中状态
        if (selectedEdge.value && selectedEdge.value.id === change.id) {
          selectedEdge.value = null
        }
      } else if (change.type === 'update') {
        edges.value = edges.value.map(edge =>
          edge.id === change.id ? { ...edge, ...change.item } : edge
        )
      }
    })
  }
  
  // 节点点击处理
  const handleNodeClick = (event) => {
    const { node } = event
    // 点击节点时取消边的高亮
    clearEdgeSelection()
    message.info(`点击节点: ${node.data.label} (ID: ${node.id})`)
  }

  // 新增：边点击处理
  const handleEdgeClick = (event) => {
    const { edge } = event
    selectedEdge.value = edge
    updateEdgesStyle()
    message.info(`点击边: ${edge.source} → ${edge.target} (ID: ${edge.id})`)
  }

    // 新增：画布点击处理（点击空白区域）
  const handleCanvasClick = (event) => {
    clearEdgeSelection()
  }

    // 新增：清除边选中状态
  const clearEdgeSelection = () => {
    if (selectedEdge.value) {
      selectedEdge.value = null
      updateEdgesStyle()
    }
  }

  // 新增：更新所有边的样式，实现高亮效果
  const updateEdgesStyle = () => {
    edges.value = edges.value.map(edge => {
      const isSelected = selectedEdge.value && selectedEdge.value.id === edge.id
      
      return {
        ...edge,
        style: {
          ...edge.style,
          stroke: isSelected ? '#2080f0' : '#666',
          strokeWidth: isSelected ? 3 : 2,
          strokeDasharray: isSelected ? '5,5' : 'none'
        },
        labelStyle: {
          ...edge.labelStyle,
          fontWeight: isSelected ? 'bold' : 'normal',
          fill: isSelected ? '#2080f0' : '#666'
        },
        // 添加选中状态的类名
        class: isSelected ? 'edge-selected' : ''
      }
    })
  }
  
  // 连接处理
  const handleConnect = (connection) => {
  // 获取连接点的颜色
  const edgeColor = getConnectionColor(connection);
  
  const newEdge = {
    ...connection,
    id: `edge-${connection.source}-${connection.target}-${Date.now()}`,
    style: { 
      stroke: edgeColor,
      strokeWidth: 2
    },
    type: 'smoothstep',
    data: {
      sourcePin: connection.sourceHandle,
      targetPin: connection.targetHandle,
      color: edgeColor
    }
  };
  
  edges.value = [...edges.value, newEdge];
  message.success('连接创建成功');
}

// 新增：根据连接点获取颜色
const getConnectionColor = (connection) => {
  // 优先使用源连接点的颜色
  const sourceNode = nodes.value.find(node => node.id === connection.source);
  if (sourceNode && sourceNode.data.connectors) {
    const pinInfo = findPinInfo(sourceNode.data.connectors, connection.sourceHandle);
    if (pinInfo) {
      return getPinColor(pinInfo.type);
    }
  }
  
  // 备用：使用目标连接点的颜色
  const targetNode = nodes.value.find(node => node.id === connection.target);
  if (targetNode && targetNode.data.connectors) {
    const pinInfo = findPinInfo(targetNode.data.connectors, connection.targetHandle);
    if (pinInfo) {
      return getPinColor(pinInfo.type);
    }
  }
  
  return '#666'; // 默认颜色
}

// 新增：根据连接点ID查找针脚信息
const findPinInfo = (connectors, handleId) => {
  for (const connector of connectors) {
    for (const pin of connector.pins) {
      const pinHandleId = `${connector.id}-${pin.id}`;
      if (pinHandleId === handleId) {
        return pin;
      }
    }
  }
  return null;
}
  
  return {
    nodes,
    edges,
    selectedNodeType,
    selectedEdge,
    handleNodesChange,
    handleEdgesChange,
    handleNodeClick,
    handleEdgeClick,
    handleCanvasClick,
    handleConnect
  }
}